package spring.data.jpa.repository.factory;

import java.io.Serializable;

import javax.persistence.EntityManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;
import org.springframework.util.Assert;

import spring.data.jpa.freemarker.FreemarkerResourceContext;

public class SimpleJpaRepositoryFactoryBean<T extends JpaRepository<S, ID>, S, ID extends Serializable>
        extends JpaRepositoryFactoryBean<T, S, ID> {

    private Class<? extends S> domainClass;
    private Class<? extends T> repositoryInterface;
    private Class<?> repositoryClass;
    private FreemarkerResourceContext freemarkerContext;

    /**
     * Spring 原生有写repository
     * @param repositoryInterface
     */
    public SimpleJpaRepositoryFactoryBean(Class<? extends T> repositoryInterface) {
        super(repositoryInterface);
        this.repositoryInterface = repositoryInterface;
    }

    /**
     * 扩展，没有写repository时，根据domain来生成
     * @param repositoryInterface
     * @param domainClass
     */
    public SimpleJpaRepositoryFactoryBean(Class<? extends T> repositoryInterface, Class<? extends S> domainClass) {
        super(repositoryInterface);
        this.domainClass = domainClass;
        this.repositoryInterface = repositoryInterface;
    }

    public void setDomainClass(Class<? extends S> domainClass) {
        Assert.notNull(domainClass, "DomainClass must not be null");
        this.domainClass = domainClass;
    }

    public void setRepositoryInterface(Class<? extends T> repositoryInterface) {
        this.repositoryInterface = repositoryInterface;
    }
    
    public void setRepositoryClass(Class<?> repositoryClass) {
        this.repositoryClass = repositoryClass;
    }
    
    @Autowired
    public void setFreemarkerContext(FreemarkerResourceContext freemarkerContext) {
        this.freemarkerContext = freemarkerContext;
    }

    /**
     * Returns a {@link RepositoryFactorySupport}.
     * 
     * @param entityManager
     * @return
     */
    @Override
    protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) {
        if (domainClass != null) {
            return new SimpleJpaRepositoryFactory(entityManager, domainClass, repositoryInterface, repositoryClass, freemarkerContext);
        }
        return new SimpleJpaRepositoryFactory(entityManager, freemarkerContext);
    }

}
